/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-03-10
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-04-15
 * @Description: 
 */
import 'package:chat_client/screens/mobile/login/login_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;

//
import 'package:chat_client/router/router.dart';
//
import 'package:chat_client/repositories/auth_repository.dart';
//
import 'package:chat_client/services/user_service.dart';
import 'package:chat_client/services/contact_service.dart';
import 'package:chat_client/services/group_service.dart';
import 'package:chat_client/services/socket/socket_service.dart';
import 'package:chat_client/services/socket/conversation_service.dart';
import 'package:chat_client/services/socket/notify_service.dart';
//
import 'package:chat_client/utils/show_messae.dart' show popError;
import 'package:chat_client/widgets/c_loading.dart';

class NetworkManagerProvider extends ChangeNotifier {
  final AuthRepository _authRepository = AuthRepository.instance;

  // 网络链接状况
  bool _networkConnect = true;

  bool get network => _networkConnect;

  // 初始化
  NetworkManagerProvider() {
    Future.delayed(Duration(seconds: 1), () => init());
  }

  Future<void> init() async {
    try {
      Loading.show(message: '正在加载');
      await _loadBasicInfo();
      startSocket();
    } catch (e) {
      print(e);
    } finally {
      Loading.hide();
    }
  }

  //1. 按需拉取所有远程消息
  Future<void> _loadBasicInfo() async {
    /// 1. 已经初始化本地
    if (_authRepository.isInitLocalStore != null ||
        _authRepository.isInitLocalStore == true) {
      return;
    }

    /// 2. 未初始化

    // 远程用户个人信息
    await UserService.instance.getRemoteUserInfo();
    // 远程好友申请数据
    await ContactService.instance.getRemoteFriendRequestList();
    // 远程群聊数据
    await GroupService.instance.getRometeGroupList();
    // 远程好友数据
    await ContactService.instance.getRemoteContactList();
    // 远程聊天信息
    await ConversationService.instance.getRemoteConversationList();

    // 标记已储存
    await _authRepository.setLocalStore(true);
  }

  // 2. 注册socket.client
  Future<void> startSocket() async {
    try {
      // 注册socket监听器
      addEventListener() {
        ConversationService.instance.register();
        NotifyService.instance.register();
        // _conversationService.getRemoteConversationList(offonline: true);
      }
      // 注册ping监听器监听网络

      void switchNetwork({required bool netState}) {
        _networkConnect = netState;
        notifyListeners();
      }

      // 启动socket
      SocketService.instance.initSocket(addEventListener, switchNetwork);
    } catch (e) {
      popError('socket启动失败', e.toString());
    }
  }
}
